package gaej.example.contact.server;

import gaej.example.contact.client.Dirigent;
import gaej.example.contact.client.Persoon;

import java.util.List;

import javax.jdo.PersistenceManager;
import gaej.example.contact.server.PmfSingleton;

public class DirigentDAOJdo implements DirigentDAO {

	public void addDirigent(Dirigent dirigent) {
		PersistenceManager pm = PmfSingleton.get().getPersistenceManager();
		try {
			Persoon persoon = dirigent.getPersoon();
			pm.makePersistent(dirigent);
		} finally {
			pm.close();
		}
	}

	@SuppressWarnings("unchecked")
	public List<Dirigent> listDirigenten() {
		PersistenceManager pm = PmfSingleton.get().getPersistenceManager();
		String query = "select from " + Dirigent.class.getName();
		return (List<Dirigent>) pm.newQuery(query).execute();
	}

	public void removeDirigent(Dirigent dirigent) {
		PersistenceManager pm =PmfSingleton.get().getPersistenceManager();
		try {
			pm.currentTransaction().begin();

			// We don't have a reference to the selected Object.
			// So we have to look it up first,
			dirigent = pm.getObjectById(Dirigent.class, dirigent.getDirigentNr());
			pm.deletePersistent(dirigent);

			pm.currentTransaction().commit();
		} catch (Exception ex) {
			pm.currentTransaction().rollback();
			throw new RuntimeException(ex);
		} finally {
			pm.close();
		}
	}

	public void updateDirigent(Dirigent dirigent) {
		PersistenceManager pm = PmfSingleton.get().getPersistenceManager();
		
		Persoon persoon = dirigent.getPersoon();
		
		String naam = persoon.getNaam();
		String land = persoon.getLand();
		
		String richting = dirigent.getRichting();
		String klasse = dirigent.getKlasse();


		try {
			pm.currentTransaction().begin();
			// We don't have a reference to the selected Product.
			// So we have to look it up first,
			dirigent = pm.getObjectById(Dirigent.class, dirigent.getDirigentNr());
			persoon = dirigent.getPersoon();
			persoon.setNaam(naam);
			persoon.setLand(land);
			dirigent.setPersoon(persoon);
			dirigent.setRichting(richting);
			dirigent.setKlasse(klasse);

			pm.makePersistent(dirigent);
			pm.currentTransaction().commit();
		} catch (Exception ex) {
			pm.currentTransaction().rollback();
			throw new RuntimeException(ex);
		} finally {
			pm.close();
		}
	}

}
